import { Graph } from '@antv/x6'
import '@antv/x6-vue-shape'
const Hierarchy = require('@antv/hierarchy');
import NodeElement from '../components/NodeElement';
import PagingNode from '../components/PagingNode';


import { debounce } from '../lib/utils';

class ChartGraph {
  constructor(el, minimapId) {
    this.registerNode()
    this.graph = null
    this.nodeRightClick = null
    this.rootId = null
    this.init(el, minimapId)
    this.onWindowResize()
  }
  on(name, event) {
    this[name] = event
  }
  init(el, minimapId) {
    this.el = el
    const container = document.getElementById(el)
    const minimapContainer = document.getElementById(minimapId)
    const width = container.scrollWidth - 10
    const height = container.scrollHeight - 10
    this.graph = new Graph({
      container: container,
      width: width,
      height: height,
      sorting: 'approx',
      interacting: false,
      minimap: {
        enabled: true,
        container: minimapContainer,
        width: 300,
        height: 200
      },
      panning: {
        enabled: true,
        eventTypes: ['leftMouseDown', 'mouseWheel']
      },
      background: {
        color: '#ffffff'
      },
      grid: {
        size: 10, // 网格大小 10px
        visible: true // 渲染网格背景
      },
      mousewheel: {
        enabled: true,
        modifiers: 'ctrl',
        minScale: 0.2
      },
      selecting: {
        enabled: true,
        multiple: true,
        rubberEdge: true,
        rubberNode: true,
        modifiers: 'shift',
        rubberband: true
      },
      connecting: {
        // anchor: 'orth',
        connector: 'rounded',
        connectionPoint: 'boundary',
        router: {
          name: 'er',
          args: {
            offset: 50,
            direction: 'H'
          }
        },
        createEdge() {
          return this.graph.createEdge({
            shape: 'dag-edge',
            attrs: {
              line: {
                strokeDasharray: null
              }
            },
            zIndex: -1
          })
        }
      }
    })
  }
  setRoot(id) {
    this.rootId = id
  }
  registerNode() {
    const vm = this
    Graph.registerVueComponent('NodeElement', {
      template: `<node-element  @right="nodeRightClick" />`,
      width: 200,
      height: 50,
      components: {
        NodeElement
      },
      methods: {
        nodeRightClick(data) {
          vm.nodeRightClick(data)
        }
      }
    }, true)

    Graph.registerVueComponent('PagingNode', {
      template: `<paging-node @right="nodeRightClick" />`,
      width: 220,
      height: 320,
      components: {
        PagingNode
      },
      methods: {
        nodeRightClick(data){
          vm.nodeRightClick(data)
        }
      }
    }, true)

}


  onWindowResize() {
    const resize = debounce(() => {
      this.resize()
    }, 200);
    window.addEventListener('resize', resize)
  }

  resize() {
    const container = document.getElementById('chart-container')
    console.log(container);
    const width = container.clientWidth
    const height = container.clientHeight
    this.graph.resize(width, height)
    this.graph.centerContent()
  }
  render(data) {
    const cells = this.formatterLayoutData(data)
    this.graph.resetCells(cells)
    this.graph.centerContent()
  }
  // 生成渲染数据
  formatterLayoutData(data) {
    const result = Hierarchy.compactBox(data, {
      direction: 'H',
      getHeight(d) {
        if (d.nodeType === 'paging'){
          return 328
        }else{
          return 50
        }
      },
      getWidth: () => 60,
      getHGap: () => 100,
      getVGap: () => 4,
      getSide: (d) => {
        if (d.data.levelType === 1) {
          return 'left'
        } else {
          return 'right'
        }
      }
    })
    return this.createCells(result)
  }
  // 设置 根接为画布重新
  resetCenter() {
    const rootCell = this.graph.getCellById(this.rootId)
    this.graph.centerCell(rootCell)
  }
  // 生成Node和Edge
  createCells(HierarchyData) {
    const CellList = []
    const create = (HierarchyItem) => {
      const { data, children } = HierarchyItem
      // 创建Node
      let Node = {}
      if (data.nodeType === 'paging'){
        Node = this.graph.createNode({
          id: data.id,
          shape: 'vue-shape',
          x: HierarchyItem.x,
          y: HierarchyItem.y,
          width: 220,
          height: 320,
          component: 'PagingNode',
          data: HierarchyItem.data
        })
      }else{
        Node = this.graph.createNode({
          id: data.id,
          shape: 'vue-shape',
          x: HierarchyItem.x,
          y: HierarchyItem.y,
          width: 200,
          height: 42,
          component: 'NodeElement',
          data: HierarchyItem.data
        })
      }
      CellList.push(Node)
      if (!children || children.length === 0) return
      children.forEach((item) => {
        const { id, data } = item
        let source = ''
        let target = ''
        if (data.levelType === 1) {
          source = id
          target = HierarchyItem.id
        } else {
          source = HierarchyItem.id
          target = id
        }
        let color = ''
        if (data.levelType === 1) {
          color = '#e6a23c'
        } else if (data.levelType === 2) {
          color = '#1e9fff'
        } else {
          color = '#ff4d4f'
        }

        // 创建Edge
        const Edges = this.graph.createEdge({
          attrs: {
            line: {
              stroke: color,
              strokeWidth: 2,
              strokeDasharray: null
            }
          },
          source: {
            cell: source
          },
          target: {
            cell: target
          },
          data: {
            color: color,
            levelType: data.levelType
          }
        })
        CellList.push(Edges)
        create(item)
      })
    }
    create(HierarchyData)
    return CellList
  }
}

export default ChartGraph
